/**
 * Copyright (c) 快宝网络 kuaidihelp.com Co., Ltd. All Rights Reserved 禁止外泄以及用于其它的商业用途
 */

import React, { useRef, useState } from 'react';
import DragTable from '@/components/DragTable';
import ProTable from '@ant-design/pro-table';
import { ModalForm } from '@ant-design/pro-form';
import KbApplyModal from '@/components/_pages/Finance/approval/components/KbApplyModal';
import KbDetailModal from '@/components/_pages/Finance/approval/components/KbDetailModal';
import type { ActionType, ProColumns } from '@ant-design/pro-table';
import type { ProFormInstance } from '@ant-design/pro-form';
import { valueEnumArray } from '@/components/_pages/Finance/index.config';
import { useRangePicker } from '@/utils/hooks/rangePicker';
import moment, { Moment } from 'moment';
import { getTransferData, transferUpdate, downloadExcel } from '@/services/Finance/approval';
import { Button, message, Space, Typography } from 'antd';
import { isString } from 'lodash';

const { Paragraph, Title } = Typography;
const Index: React.FC = () => {
  const [visible, setVisible] = useState<boolean>(false);
  const [detailVisible, setDetailVisible] = useState<boolean>(false);
  const [detailRecord, setDetailRecord] = useState<{ [name: string]: string }>({});
  const [recordItem, setRecordItem] = useState<{ [name: string]: string }>({});
  const actionRef = useRef<ActionType>();
  const formRef = useRef<ProFormInstance>();
  const RangePicker = useRangePicker({
    title: '选择日期',
    valuesKeys: ['s_date', 'e_date'],
    defaultRange: 30,
    limitValueRange: 365,
  });

  const handleOption = (record: { [name: string]: string }) => {
    setRecordItem(record);
    setVisible(true);
  };
  const handleCloseModal = () => {
    setRecordItem({});
    setVisible(false);
  };
  const handleOpenDetailModal = (record: { [name: string]: string }) => {
    setDetailRecord(record);
    setDetailVisible(true);
  };
  const handleCloseDetailModal = () => {
    setDetailRecord({});
    setDetailVisible(false);
  };
  const handleAdopt = () => {
    transferUpdate({ id: recordItem.id, status: 1 }).then((res) => {
      const { code, msg } = res;
      if (code == 0) {
        message.success('提交成功');
        setVisible(false);
        actionRef.current?.reload();
      } else {
        message.error(msg);
      }
    });
  };
  const handleFail = () => {
    setVisible(false);
    actionRef.current?.reload();
  };

  const columns: ProColumns[] = [
    RangePicker,
    {
      title: '审核状态',
      dataIndex: 'type',
      valueType: 'radioButton',
      initialValue: '0',
      hideInTable: true,
      valueEnum: new Map<string, any>(valueEnumArray),
      fieldProps: {
        onChange: () => formRef.current?.submit(),
      },
    },
    {
      dataIndex: 'keyword',
      hideInTable: true,
      valueType: 'text',
      fieldProps: {
        placeholder: '可输入申请网点编号、申请网点名称查询',
      },
    },
    {
      title: '申请日期',
      dataIndex: 'created_at',
      width: 100,
      search: false,
      align: 'center',
      ellipsis: true,
    },
    {
      title: '申请网点编号',
      dataIndex: 'index_shop_id',
      width: 100,
      search: false,
      align: 'center',
      ellipsis: true,
    },
    {
      title: '申请网点',
      dataIndex: 'index_shop_name',
      width: 100,
      search: false,
      align: 'center',
      ellipsis: true,
    },
    {
      title: '关联开票信息（抬头）',
      dataIndex: 'invoice_title',
      width: 100,
      search: false,
      align: 'center',
      ellipsis: true,
      render: (_, record) => {
        const { invoice_title } = record;
        return (
          <Space>
            {invoice_title}
            <a onClick={handleOpenDetailModal.bind(null, record)}>详情</a>
          </Space>
        );
      },
    },
    {
      title: '申请金额',
      dataIndex: 'transfer_money',
      width: 100,
      search: false,
      align: 'center',
      ellipsis: true,
    },
    {
      title: '转账日志号',
      dataIndex: 'transfer_no',
      width: 100,
      search: false,
      align: 'center',
      ellipsis: true,
    },
    {
      title: '审核状态',
      dataIndex: 'status',
      width: 100,
      search: false,
      valueEnum: {
        '0': '未审核',
        '1': '已通过',
        '-1': '未通过',
      },
      align: 'center',
      ellipsis: true,
    },
    {
      title: '操作',
      valueType: 'option',
      width: 100,
      fixed: 'right',
      align: 'center',
      render: (_, record) => {
        const { id, status, admin_commnet } = record;
        if (`${status}` === '0') {
          return <a onClick={handleOption.bind(null, record)}>审核</a>;
        } else if (`${status}` === '-1') {
          return (
            <KbApplyModal
              placeholder={admin_commnet}
              onCallBack={handleFail}
              queryData={{ id: id, status: -1, type: 'updatecomment' }}
            >
              <a>审核未通过原因</a>
            </KbApplyModal>
          );
        } else {
          return;
        }
      },
    },
  ];
  const formatDataMap = (date: Moment) => {
    if (!date) return;
    return isString(date) ? date : moment(date).format('YYYY-MM-DD');
  };
  const onDownload = () => {
    const { dates, keyword, type } = formRef.current?.getFieldsValue() || {};
    const [s_date, e_date] = dates;
    const queryData = {
      s_date: formatDataMap(s_date),
      e_date: formatDataMap(e_date),
      keyword,
      type,
    };
    downloadExcel(queryData).then((res) => {
      const { code, data, msg } = res;
      if (code == 0) {
        window.open(data, '_blank');
      } else {
        message.error(msg);
      }
    });
  };
  const onFinish = async (values: any) => {
    const { current: page } = values;
    delete values.current;
    const { code, data, msg } = await getTransferData({ ...values, page });
    if (code == 0) {
      const { result, total } = data;
      return {
        data: result,
        total: total,
      };
    }
    message.error(msg);
    return {
      data: [],
    };
  };
  return (
    <>
      <DragTable>
        <ProTable
          actionRef={actionRef}
          formRef={formRef}
          rowKey='id'
          request={onFinish}
          columns={columns}
          options={false}
          scroll={{ x: 1200 }}
          pagination={{
            pageSize: 20,
            showSizeChanger: false,
          }}
          search={{
            collapseRender: () => <></>,
            collapsed: false,
            optionRender: (_, __, dom) => {
              return [
                ...dom.reverse(),
                <Button key='download' type='primary' onClick={onDownload}>
                  下载
                </Button>,
              ];
            },
          }}
        />
      </DragTable>
      <ModalForm
        title='网点开票申请'
        width={400}
        visible={visible}
        modalProps={{
          destroyOnClose: true,
          onCancel: handleCloseModal,
        }}
        submitter={{
          render: () => [
            <Button type='primary' onClick={handleAdopt}>
              审核通过
            </Button>,
            <KbApplyModal onCallBack={handleFail} queryData={{ id: recordItem.id, status: -1 }}>
              <Button>审核不通过</Button>
            </KbApplyModal>,
          ],
        }}
      >
        <Paragraph type='secondary'>
          申请金额：{' '}
          <Title level={2} type='danger' style={{ display: 'inline' }}>
            {recordItem?.transfer_money}
          </Title>
          元，是否审核通过？
        </Paragraph>
      </ModalForm>
      <KbDetailModal
        visible={detailVisible}
        id={detailRecord.shop_info_id}
        onVisibleChange={handleCloseDetailModal}
      />
    </>
  );
};

export default Index;
